<template>
  <div v-if="!isLoading" class="admin-home">
    <a-row :gutter="16">
      <a-col :span="6">
        <a-card class="stat-card">
          <template #title>
            <span class="card-title">门店总数</span>
          </template>
          <div class="stat-value">{{ storeCount }}</div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <template #title>
            <span class="card-title">商品总数</span>
          </template>
          <div class="stat-value">{{ productCount }}</div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <template #title>
            <span class="card-title">分类总数</span>
          </template>
          <div class="stat-value">{{ categoryCount }}</div>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <template #title>
            <span class="card-title">模板总数</span>
          </template>
          <div class="stat-value">{{ templateCount }}</div>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16" style="margin-top: 16px">
      <a-col :span="12">
        <a-card title="最近添加的商品">
          <a-table
            :columns="recentProductColumns"
            :data-source="recentProducts"
            :pagination="false"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'image'">
                <img :src="record.imageUrlList[0]" class="product-image" v-if="record.imageUrlList && record.imageUrlList.length > 0" />
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card title="系统信息">
          <a-descriptions :column="1" size="small">
            <a-descriptions-item label="系统版本">v1.0.0</a-descriptions-item>
            <a-descriptions-item label="最后更新">2024-03-21</a-descriptions-item>
            <a-descriptions-item label="技术支持">support@example.com</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { listAllStores } from '@/api/store';
import { listAllProduct } from '@/api/product';
import { listPermission } from '@/api/permission';
import { h } from 'vue';
import {
  HomeOutlined,
  AppstoreOutlined,
  SettingOutlined,
  CrownOutlined,
  TagsOutlined,
  ToolOutlined,
  ShoppingOutlined,
  FileTextOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons-vue';
import type { MenuProps } from 'ant-design-vue';
import { useRouter } from 'vue-router';

// 统计数据
const storeCount = ref(0);
const productCount = ref(0);
const categoryCount = ref(0);
const templateCount = ref(0);

// 导航菜单项
const navItems = ref<MenuProps['items']>([]);

const navItemMap: { [key: string]: NonNullable<MenuProps['items']>[number] } = {
  'adminHome': {
    key: '/admin/adminHome',
    icon: () => h(HomeOutlined),
    label: '主页',
    title: '主页',
  },
  'Store_Manage': {
    key: '/admin/store',
    icon: () => h(SettingOutlined),
    label: '门店管理',
    title: '门店管理',
  },
  'Category_Manage': {
    key: '/admin/category',
    icon: () => h(TagsOutlined),
    label: '分类管理',
    title: '分类管理',
  },
  'Product_Manage': {
    key: '/admin/product',
    icon: () => h(ShoppingOutlined),
    label: '商品管理',
    title: '商品管理',
  },
  'Product_Setting': {
    key: '/admin/product-config',
    icon: () => h(AppstoreOutlined),
    label: '商品配置',
    title: '商品配置',
  },
  'Param_Manage': {
    key: '/admin/param',
    icon: () => h(ToolOutlined),
    label: '参数管理',
    title: '参数管理',
  },
  'Template_Manage': {
    key: '/admin/template',
    icon: () => h(CrownOutlined),
    label: '模板管理',
    title: '模板管理',
  },
  'Store_Order': {
    key: '/admin/store-orders',
    icon: () => h(FileTextOutlined),
    label: '门店订单',
    title: '门店订单',
  },
  'Permission_Manage': {
    key: '/admin/permission',
    icon: () => h(SafetyCertificateOutlined),
    label: '权限管理',
    title: '权限管理',
  },
  'Employee_Manage': {
    key: '/admin/employee',
    icon: () => h(SafetyCertificateOutlined),
    label: '人员管理',
    title: '人员管理',
  },
  'Role_Manage': {
    key: '/admin/role',
    icon: () => h(SafetyCertificateOutlined),
    label: '角色管理',
    title: '角色管理',
  }
};

// 添加加载状态
const isLoading = ref(true);

// 获取导航菜单
const fetchNavItems = async () => {
  try {
    const res = await listPermission();
    if (res.data.code === 200) {
      const havaStore = res.data.data.havaStore;
      if(havaStore === false) {
        // 没有门店, 跳转到空页面
        router.replace('/empty');
        return;
      }

      const permissionList = res.data.data.permissionList;
      navItems.value = permissionList.map((key: string) => navItemMap[key] || null).filter(Boolean);
      console.log('导航菜单项:', navItems.value);

      // 检查是否有导航项
      if (navItems.value && navItems.value.length > 0) {
        // 获取第一个导航项的路由
        const firstNavItem = navItems.value[0];
        if (firstNavItem && typeof firstNavItem.key === 'string') {
          // 跳转到第一个导航项
          router.push(firstNavItem.key);
        }
      } else {
        // 没有导航项，跳转到空页面
        router.replace('/empty');
      }
    }
  } catch (error) {
    console.error('获取导航菜单失败:', error);
    // 发生错误时也跳转到空页面
    router.replace('/empty');
  } finally {
    // 只有在不需要跳转时才显示内容
    if (router.currentRoute.value.path === '/admin/adminHome') {
      isLoading.value = false;
    }
  }
};

// 最近商品列表
const recentProducts = ref([]);
const recentProductColumns = [
  {
    title: '商品图片',
    dataIndex: 'imageUrlList',
    key: 'image',
    width: 60,
  },
  {
    title: '商品名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '价格',
    dataIndex: 'basePrice',
    key: 'price',
  },
  {
    title: '添加时间',
    dataIndex: 'create_time',
    key: 'create_time',
  },
];

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 加载门店数量
    const storeResponse = await listAllStores();
    if (storeResponse.data.code === 200) {
      storeCount.value = storeResponse.data.data.length;
    }

    // 加载商品数量
    const productResponse = await listAllProduct(100, 1);
    if (productResponse.data.code === 200) {
      productCount.value = productResponse.data.data.list.length;
      recentProducts.value = productResponse.data.data.list.slice(0, 5);
    }
  } catch (error) {
    console.error('加载统计数据失败:', error);
  }
};

const router = useRouter();

onMounted(async () => {
  await fetchNavItems();
  // 只有在不需要跳转时才加载统计数据
  if (router.currentRoute.value.path === '/admin/adminHome') {
    loadStatistics();
  }
});
</script>

<style scoped>
.admin-home {
  padding: 24px;
}

.stat-card {
  height: 120px;
}

.card-title {
  font-size: 14px;
  color: #666;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1890ff;
  margin-top: 8px;
}

.product-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
}

:deep(.ant-card-head) {
  min-height: 48px;
}

:deep(.ant-descriptions-item-label) {
  color: #666;
}
</style> 